<template>
  <div>
    <el-empty
      v-if="dataList.length == 0"
      description="这里什么都没有"
    ></el-empty>
    <div v-else>
      <div class="close-container">
        <div class="user-info">
          <span class="user-name">{{ dataList[0].userName }}</span>
          <span class="job-number">（{{ dataList[0].jobNumber }}）</span>
        </div>
        <div class="info-row">联系方式：{{ dataList[0].phoneNumber }}</div>
        <div class="info-row">
          进修期限：{{ registerStartDate }} ~ {{ registerEndDate }}
        </div>
        <div class="info-row">请假总时长：{{ getTotalLeaveDuration() }}天</div>
        <div class="info-row">销假总时长：{{ closeLeave }}天</div>
        <div class="line"></div>

        <div v-for="(item, index) in dataList" :key="item.id">
          <div class="section-title">销假时段{{ index + 1 }}：</div>
          <div class="date-range">
            {{ item.leaveStartDate }} ~ {{ item.leaveEndDate }}
          </div>
          <div class="form-row">
            <span class="label">销假时长：</span>
            <el-select
              v-model="item.closeDuration"
              placeholder="请选择销假时长"
              class="duration-select"
            >
              <el-option label="请选择销假时长" value=""></el-option>
              <el-option
                v-for="option in item.closeDurationOptions"
                :key="option"
                :label="option + '天'"
                :value="option"
              ></el-option>
            </el-select>
          </div>
          <div class="form-row">
            <span class="label">销假原因：</span>
            <el-input
              type="textarea"
              v-model="item.closeCause"
              placeholder="请输入销假原因"
              :rows="3"
              class="cause-input"
              maxlength="100"
              show-word-limit
            ></el-input>
          </div>
          <div class="section-divider" v-if="index < dataList.length - 1"></div>
        </div>
      </div>
    </div>
    <div class="button-container">
      <el-button type="primary" @click="submitForm" v-if="dataList.length > 0"
        >确 定</el-button
      >
      <el-button @click="closeDialog">取 消</el-button>
    </div>
  </div>
</template>

<script>
import { consts } from "@/api/business/consts";
import { batchSaveLoseLeave } from "@/api/business/registerBase";
import { listAllRegisterLeave } from "@/api/business/registerLeave";

export default {
  props: {
    registerId: null,
    registerStartDate: null,
    registerEndDate: null,
    closeLeave: null,
  },
  data() {
    return {
      dataList: [],
      queryParams: {
        registerId: null,
      },
      leaveStatusList: consts.leaveStatusList,
      leaveTypeList: consts.leaveTypeList,
      rules: {
        closeDuration: [
          { required: true, message: "销假时长不能为空", trigger: "blur" },
        ],
        closeDate: [
          { required: true, message: "销假时间不能为空", trigger: "blur" },
        ],
        closeCause: [
          { required: true, message: "销假原因不能为空", trigger: "blur" },
        ],
      },
    };
  },
  mounted() {
    this.queryParams.registerId = this.registerId;
    this.getList();
  },
  methods: {
    getDaysBetweenDates(startDateStr, endDateStr) {
      if (!startDateStr || !endDateStr) {
        return 0;
      }

      // 确保输入是字符串格式
      const startStr =
        typeof startDateStr === "string"
          ? startDateStr
          : startDateStr.toISOString();
      const endStr =
        typeof endDateStr === "string" ? endDateStr : endDateStr.toISOString();

      // 通过截取日期字符串的日期部分(YYYY-MM-DD)来创建Date对象，以忽略时间部分的影响
      const startDate = new Date(startStr.substring(0, 10));
      const endDate = new Date(endStr.substring(0, 10));

      // 计算两个日期之间的毫秒差
      const diffTime = endDate.getTime() - startDate.getTime();

      // 将毫秒差转换为天数
      const diffDays = diffTime / (1000 * 60 * 60 * 24);

      // 加1以包含开始日期和结束日期
      return diffDays + 1;
    },
    getList() {
      listAllRegisterLeave(this.queryParams).then((response) => {
        let list = response.data;
        for (let i = 0; i < list.length; i++) {
          const leaveDurationDays = this.getDaysBetweenDates(
            list[i].leaveStartDate,
            list[i].leaveEndDate
          );

          list[i].closeDate = list[i].leaveEndDate;
          list[i].closeDuration = list[i].closeDuration || ""; // 默认选中完全销完
          list[i].closeCause = list[i].closeCause || "";
          list[i].closeDurationOptions = Array.from(
            { length: leaveDurationDays },
            (_, i) => i + 1
          );
        }
        this.dataList = list;
      });
    },
    getTotalLeaveDuration() {
      if (!this.dataList || this.dataList.length === 0) return 0;
      return this.dataList.reduce(
        (total, item) => total + (item.leaveDuration || 0),
        0
      );
    },

    submitForm() {
      // 构建请求参数
      const leaveItems = this.dataList.map((item) => ({
        id: item.id,
        registerId: item.registerId,
        closeCause: item.closeCause,
        closeDate: item.closeDate,
        closeDuration: item.closeDuration,
      }));

      const params = {
        leaveItems: leaveItems,
      };

      batchSaveLoseLeave(params)
        .then((response) => {
          this.getList();
          this.$modal.msgSuccess("销假完成");
          this.closeDialog();
        })
        .catch((error) => {
          this.$modal.msgError("销假失败，请重试");
        });
    },
    closeDialog() {
      this.$emit("close");
    },
  },
};
</script>
<style lang="scss" scoped>
.close-container {
  font-size: 16px;
  line-height: 30px;
  padding: 15px;
  background-color: #fff;
  border-radius: 5px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

  .user-info {
    margin-bottom: 10px;

    .user-name {
      font-size: 18px;
      font-weight: bolder;
      color: #333;
    }

    .job-number {
      font-size: 14px;
      color: #666;
      margin-left: 5px;
    }
  }

  .info-row {
    font-size: 14px;
    color: #666;
    margin-bottom: 5px;
  }

  .line {
    margin: 15px 0;
    border-bottom: 2px dashed #f2f3f5;
  }

  .section-title {
    font-size: 16px;
    font-weight: bold;
    color: #333;
    margin: 15px 0 10px 0;
  }

  .date-range {
    font-size: 14px;
    color: #666;
    margin-bottom: 10px;
  }

  .form-row {
    display: flex;
    align-items: flex-start;
    margin-bottom: 15px;

    .label {
      width: 80px;
      font-size: 14px;
      color: #666;
      line-height: 32px;
    }

    .duration-select {
      width: 220px;
    }

    .cause-input {
      width: calc(100% - 80px);
    }
  }

  .section-divider {
    margin: 20px 0;
    border-bottom: 1px solid #ebeef5;
  }
}

.button-container {
  text-align: center;
  margin-top: 20px;
}
</style>
